var express = require('express')
var router = express.Router()
const { getAll, getOne, exec } = require('../db')

/**
 * 分页查询所有事件
 * GET /event
 */
router.get('/', async (req, res, next) => {
  const { page, size, keyword } = req.query
  const offset = (page - 1) * size
  if (!keyword) {
    let sql = `select * from gg_event limit ${offset},${size}`
    const data = await getAll(sql)
    sql = `select count(*) as total from gg_event`
    const { total } = await getOne(sql)
    res.send({
      code: 0,
      message: '获取分页事件成功',
      result: {
        total,
        data,
      },
    })
  } else {
    let sql = `select * from gg_event where event_type like '%${keyword}%'`
    const data = await getAll(sql)
    sql = `select count(*) as total from gg_event`
    const { total } = await getOne(sql)
    res.send({
      code: 0,
      message: '搜索成功',
      result: {
        total,
        data,
      },
    })
  }
})

/**
 *添加一个事件信息
 * POST /event
 */
router.post('/', async function (req, res, next) {
  try {
    // 1.解析req请求体的参数
    const { user_id, event_type, event_address, event_describe } = req.body
    let sql = `insert into gg_event (user_id, event_type, event_address, event_describe) values('${user_id}','${event_type}','${event_address}','${event_describe}')`
    const data = await exec(sql)
    // 返回结果
    res.send({
      code: 0,
      msg: '新增事件成功',
      result: {
        event_id: data.insertId,
        user_id,
        event_type,
        event_address,
        event_describe,
      },
    })
  } catch (error) {
    console.log(error)
  }
})

/**
 *修改一个事件
 *PUT /event/:id
 *
 */
router.put('/:id', async (req, res, next) => {
  try {
    const { id } = req.params
    const { user_id, event_type, event_address, event_describe, event_check } =
      req.body
    let sql = `update gg_event set event_check ='${event_check}' where event_id =${id}`
    const data = await exec(sql)
    res.send({
      code: 0,
      message: '事件更新成功',
      result: {
        event_id: id,
        user_id,
        event_type,
        event_address,
        event_describe,
        event_check,
      },
    })
  } catch (error) {
    console.log(error)
  }
})

/**
 *删除一个事件
 *DELETE /event/:id
 */
router.delete('/:id', async function (req, res, next) {
  // 1.解析req的参数
  const { id } = req.params
  try {
    // 操作数据库
    let sql = `delete from gg_event where event_id = ${id}`
    const data = await exec(sql)
    // 返回结果
    res.send({
      code: 0,
      msg: '删除事件成功',
      result: '',
    })
  } catch (e) {
    console.log(e)
  }
})

module.exports = router
